<template>
	<view>
		<u-notice-bar type="primary" :volume-icon="false" mode="horizontal" :list="list"></u-notice-bar>
		<view class="date">
			<!-- 年份 月份 -->
			<div class="month">
				<u-icon @click="weekPre" name="arrow-left"></u-icon>
				<span style="margin-left: 35rpx;margin-right: 30rpx;">
					{{ currentYear }}年{{ currentMonth }}月
				</span>
				<u-icon @click="weekNext" name="arrow-right"></u-icon>
			</div>

			<!-- 星期 -->
			<ul class="weekdays">
				<li></li>
				<li>一</li>
				<li>二</li>
				<li>三</li>
				<li>四</li>
				<li>五</li>
			</ul>
			<!-- 日期 -->
			<ul class="days">
				<li></li>
				<li @click="pick(day)" v-for="(day, index) in days" :key="index">
					<!--本月-->
					<span v-if="day.getMonth()+1 != currentMonth" class="other-month">{{ day.getDate() }}</span>
					<span v-else>
						<!--今天-->
						<span v-if="day.getFullYear() == new Date().getFullYear() && day.getMonth() == new Date().getMonth() && day.getDate() == new Date().getDate()"
						 class="active">{{ day.getDate() }}</span>
						<span v-else>{{ day.getDate() }}</span>
					</span>
				</li>
			</ul>

			<ul v-if="!hasmyocc" class="nametable" v-for="(item,index) in mainNameTable" :key="index">
				<li>{{timeorder[index].begin}}-<br>{{timeorder[index].end}}</li>
				<li v-for="(item2,index2) in mainNameTable[index]" :class="{'active':findindIndex(ind,index,index2)!=-1}" @click="handleSelect(index,index2)" :key="index2">
				</li>
			</ul>
			<ul v-if="hasmyocc" class="nametable" v-for="(item,index) in mainNameTable" :key="index">
				<li>{{timeorder[index].begin}}-<br>{{timeorder[index].end}}</li>
				<li v-for="(item2,index2) in mainNameTable[index]" :class="{'active1':myocc[0]==index&&myocc[1]==index2}" @click="handleSelect(index,index2)" :key="index2">
				</li>
			</ul>
			<view class="btn">
			<u-modal v-model="already"  :content="already_cont"></u-modal>
			<u-toast ref="uToast" />
			<div style="margin-top: 20rpx">
				<u-button class="u-m-r-5"   @click="handleReply()" plain type="primary">立即预约</u-button>
			</div>
			
		</view>
		</view>
		


	</view>


</template>

<script>
	import api from "../../utils/api.js"
	export default {
		data() {
			return {
				count:0,
				ruleback:'最多选择三个时间段',
				ind: [],
				cachetable:[],
				cache: '',
				cache2: '',
				show: false,
				already: false,
				already_cont: '提交成功！',
				currentYear: 1970, // 年份
				currentMonth: 1, // 月份
				currentDay: 1, // 日期
				currentWeek: 1, // 星期
				choosetime: '',
				timeorder: [],
				days: [],
				mainNameTable:[],
				arrangementForm: {
					comment: "",
					moduleIdList: [],
					occupyTimeList: [],
					timeOrderIdList: []
				},
				list: [
					'提示：报名学车最多预约三个时间段'
				],
				userid:'',
				myocc:[],
				hasmyocc:false
			}
		},
		created() {
			this.userid = uni.getStorageSync('user').id
			this.initData(null)
			if(this.currentWeek==6||this.currentWeek==7){
				this.weekNext()
			}
			this.querytimetable()
			api.gettimeorder(1).then((res) => {
					this.timeorder = res.data
					this.timeorder.sort(function(a, b) {
						return a.id - b.id
					})
				})
		},
		methods: {
			querytimetable() {
				api.getArrageList(this.days[0].getTime(),'',1).then((res) => {
					this.mainNameTable = res.data
					for(let item of this.mainNameTable){
						item.splice(5,2)
					}
					this.myocc = [];
					this.myocc = this.findismyocc();
				})
			},
			
			handleSelect(index,index2){ //index为时间段  index为周几
				if(this.hasmyocc){
					this.already_cont =  '您已提交过申请，请耐心等待管理员审批！'
					this.already = true
				}else{
				let today = new Date(new Date().setHours(0, 0, 0, 0))  //获得今天的时间
				if(today.getDay()==5){
					today.setTime(today.getTime()+3*24*60*60*1000);
				}else{
					today.setTime(today.getTime()+24*60*60*1000);
				}
				let key = this.findindIndex(this.ind,index,index2)
				if(key == -1){  //未选中，做选择处理
					if(this.ind.length<3&&this.days[index2].getTime()>=today.getTime()){
						this.ind.push([index,index2])  //选择后，做索引标记
						this.cachetable = this.ind
						this.arrangementForm.occupyTimeList.push(new Date(this.days[index2].setHours(0, 0, 0, 0)).getTime())
						this.arrangementForm.timeOrderIdList.push(this.timeorder[index].id)
					}else{
						if(this.ind.length>=3){
							this.ruleback='最多选择三个时间段'
						}
						if(this.days[index2].getTime()<today.getTime()){
							this.ruleback='只能选择今天之后的时间段'
						}
						this.showToast()
					}
				}else{//已选中，删除处理
					this.ind.splice(key,1)
					this.cachetable = this.ind
					let okey = this.findoccupyKey(new Date(this.days[index2].setHours(0, 0, 0, 0)).getTime(),this.timeorder[index],this.arrangementForm.occupyTimeList,this.arrangementForm.timeOrderIdList)
					this.arrangementForm.occupyTimeList.splice(okey,1)
					this.arrangementForm.timeOrderIdList.splice(okey,1)
				}}
				// let today = new Date(new Date().setHours(0, 0, 0, 0)).getTime()
				
			},
			findismyocc(){
				for(let timeocc in this.mainNameTable){
					for(let dayocc in this.mainNameTable[timeocc]){
						for(let item of this.mainNameTable[timeocc][dayocc].arrangementVOList){
							if(item.userId==this.userid){
								this.hasmyocc = true
								if(item.status==1){
									return [timeocc,dayocc];
								}
							}
						}
					}
				}
				return -1;
			},
			findindIndex(ind,index,index2){
				for(let key in ind){
					if(ind[key][0]==index&&ind[key][1]==index2){
						return key;
					}
				}
				return -1;
			},
			findoccupyKey(occupyTime,timeOrder,occupyTimeList,timeOrderIdList){
				for(let occupy in occupyTimeList){
					for(let Order in timeOrderIdList){
						if(occupyTimeList[occupy]==occupyTime&&timeOrderIdList[Order]==timeOrder&&occupy==Order){
							return Order;
						}
					}
				}
			},
			handleReply() {
				api.postAppointment(this.arrangementForm).then((res)=>{
					if(res.code==0){
						this.already_cont =  '提交成功！'
						this.already = true
						this.ind.length = 0
						this.hasmyocc = true
						this.arrangementForm.occupyTimeList.length = 0
						this.arrangementForm.timeOrderIdList.length = 0
						this.arrangementForm.moduleIdList.length = 0
					}else{
						this.already_cont ='请稍后再试！'
						this.already = true
					}

				})
			},
			showToast() {
				this.$refs.uToast.show({
					title: this.ruleback,
					type: 'warning ',
				})
			},
			chooseModule(e) {
				this.curModule = e[0]
			},
			formatDate(year, month, day) {
				const y = year
				let m = month
				if (m < 10) m = `0${m}`
				let d = day
				if (d < 10) d = `0${d}`
				return `${y}-${m}-${d}`
			},
			initData(cur) {
				let date = ''
				if (cur) {
					date = new Date(cur)
				} else {
					date = new Date()
				}
				this.currentDay = date.getDate() // 今日日期 几号
				this.currentYear = date.getFullYear() // 当前年份
				this.currentMonth = date.getMonth() + 1 // 当前月份
				this.currentWeek = date.getDay() // 1...6,0  // 星期几
				if (this.currentWeek === 0) {
					this.currentWeek = 7
				}
				const str = this.formatDate(this.currentYear, this.currentMonth, this.currentDay) // 今日日期 年-月-日
				this.days.length = 0
				// 今天是周日，放在第一行第7个位置，前面6个 这里默认显示一周，如果需要显示一个月，则第二个循环为 i<= 35- this.currentWeek
				/* eslint-disabled */
				for (let i = this.currentWeek - 1; i >= 0; i -= 1) {
					const d = new Date(str)
					d.setDate(d.getDate() - i)
					this.days.push(d)
				}
				for (let i = 1; i <= 7 - this.currentWeek; i += 1) {
					const d = new Date(str)
					d.setDate(d.getDate() + i)
					this.days.push(d)
				}
				this.days.pop()
				this.days.pop()
				// let today = new Date(new Date().setHours(8, 0, 0, 0)).getTime()
				let today = new Date(new Date().setHours(8, 0, 0, 0))
				if(today.getDay()==5){
					today.setTime(today.getTime()+3*24*60*60*1000);
				}else{
					today.setTime(today.getTime()+24*60*60*1000);
				}

				if(this.days.findIndex((v) => {
					return v * 1 === today.getTime()})!=-1){
						this.ind = this.cachetable
					}else{
						this.ind = []
					}
					this.querytimetable()
			},

			// 上个星期
			weekPre() {
				this.count--;
				if(this.count<0){
					this.count++;
					this.already_cont =  '只能选择近两周'
					this.already = true
					return;
				}
				const d = this.days[0] // 如果当期日期是7号或者小于7号
				d.setDate(d.getDate() - 7)
				this.initData(d)
			},

			// 下个星期
			weekNext() {
				this.count++;
				if(this.count>1){
					this.count--;
					this.already_cont =  '只能选择近两周'
					this.already = true
					return;
				}
				const d = this.days[4] // 如果当期日期是7号或者小于7号
				d.setDate(d.getDate() + 7)
				this.initData(d)
			},

			// 上一個月  传入当前年份和月份
			pickPre(year, month) {
				const d = new Date(this.formatDate(year, month, 1))
				d.setDate(0)
				this.initData(this.formatDate(d.getFullYear(), d.getMonth() + 1, 1))
			},


			// 下一個月  传入当前年份和月份 
			pickNext(year, month) {
				const d = new Date(this.formatDate(year, month, 1))
				d.setDate(35)
				this.initData(this.formatDate(d.getFullYear(), d.getMonth() + 1, 1))
			},

			// 当前选择日期
			pick(date) {
				console.log(this.days)
			},
		},
	}
</script>

<style scoped lang="scss">
	.active {
		background: #e0e0fd;
		color: #fff;
	}
	
	.active1 {
		background: #ff1100;
		color: #fff;
	}

	.date {
		height: 180rpx;
		color: #333;
		background-color: #F1F1F1;

		.month {
			font-size: 30rpx;
			text-align: center;
			padding-top: 20rpx;
		}

		.weekdays {
			display: flex;
			font-size: 28rpx;
			margin-top: 20rpx;

			li {
				flex: 1;
				text-align: center;
			}
		}

		.days {
			display: flex;
			margin-bottom: 18rpx;

			li {
				flex: 1;
				font-size: 30rpx;
				text-align: center;
				margin-top: 10rpx;
				line-height: 40rpx;

				.active {
					display: inline-block;
					width: 45rpx;
					height: 45rpx;
					color: #fff;
					border-radius: 50%;
					background-color: #fa6854;
				}

				.other-month {
					color: #e4393c;
				}
			}
		}

		.nametable {
			display: flex;

			li {

				flex: 1;
				font-size: 28rpx;
				text-align: center;
				line-height: 55rpx;
				color: #999;
				border-right: 1rpx solid #f1f1f1;
				border-bottom: 1rpx solid #f1f1f1;
				height: 120rpx;

				.other-month {
					color: #e4393c;
				}
			}
		}

		.innametable {
			display: flex;

			li {
				flex: 1;
				font-size: 28rpx;
				text-align: center;
				line-height: 50rpx;
				color: #999;
				border: 1rpx solid #f1f1f1;
				height: 50rpx;
				width: 50rpx;

				.active {
					display: inline-block;
					width: 45rpx;
					height: 45rpx;
					color: #fff;
					border-radius: 50%;
					background-color: #fa6854;
				}

				.other-month {
					color: #e4393c;
				}
			}
		}

	}

	.btn {
		margin: 0 auto;
		width: 92%;
	}

	.choosenametable {
		margin: 0 auto;
		width: 92%;
		margin-bottom: 30rpx;
	}
</style>
